package hotel.quartz.oversea.controller;

import hotel.base.oversea.constant.SwitchConstants;
import hotel.base.oversea.controller.BaseController;
import hotel.base.oversea.utils.Result;
import hotel.quartz.oversea.config.service.RedisService;
import hotel.quartz.oversea.entity.form.JobForm;
import hotel.quartz.oversea.service.JobAndTriggerService;
import lombok.extern.slf4j.Slf4j;
import org.quartz.SchedulerException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author zhangjinzheng
 * @date 2019-11-22
 */
@Slf4j
@RestController
@RequestMapping("/jobSwitchs")
public class JobSwitchsController extends BaseController {
    private String timestamp = "jobSwitchs"+String.valueOf(System.currentTimeMillis());
    private String getRedisSwCityIdNow = SwitchConstants.REDIS_SWITCH_CITY_ID_NOW;
    private String redisKeyHeadCityPageIndex = "quartz_master_hotel_job_city_page_index_";
    private String redisWaitSaveKey = SwitchConstants.REDIS_SW_MASTER_HOTEL_WAIT_SAVE;
    private String redisSwCityIdsHas = SwitchConstants.REDIS_SWITCH_CITY_IDS_HAS;
    @Autowired
    private JobAndTriggerService jobAndTriggerService;
    @Autowired
    private RedisService redisService;
    @Autowired
    private RedisTemplate redisTemplate;
    /**
     * 保存定时任务
     */
    @PutMapping(value="/ending")
    public Result<JobForm> addJob(JobForm form) {
        //已最后一页，暂停定时器,删除rediskey
        try {
            jobAndTriggerService.pauseJob(form);
            if(!StringUtils.isEmpty(getRedisCityIdNow())){
                deleteRedisOneCityIdPageIndex(getRedisCityIdNow());
            }
            deleteRedisCityIdNow();
            deleteRedisHasCityIdsMap();
            deleteRedisWaitSaveData();
            log.warn("Switchs Hotel Master Job 执行暂停！: {},{}",form.getJobGroupName(),form.getJobClassName());
        } catch (SchedulerException e) {
            log.error(e.getMessage(),e);
        }
        return new Result<>(form);
    }

    /**
     * 删除缓存的待保存数据
     * @return
     */
    public void deleteRedisWaitSaveData(){
        log.info("Switchs Hotel Master Job {} 携程母酒店定时器进入方法 deleteRedisWaitSaveData 删除当前携程母酒店定时器数据缓存",timestamp);
        redisTemplate.delete(redisWaitSaveKey);
    }
    public void deleteRedisCityIdNow(){
        redisTemplate.delete(timestamp+getRedisSwCityIdNow);
    }
    public void deleteRedisHasCityIdsMap(){
        redisTemplate.delete(redisSwCityIdsHas);
    }
    public void deleteRedisOneCityIdPageIndex(String cityId){
        redisTemplate.delete(redisKeyHeadCityPageIndex+cityId);
    }
    public String getRedisCityIdNow(){
        return (String)redisService.get(timestamp+getRedisSwCityIdNow);
    }

}
